package com.msk.web.controller.wlhy;

import com.google.common.collect.Maps;
import com.msk.common.core.controller.BaseController;
import com.msk.common.core.domain.R;
import com.msk.common.core.domain.model.LoginUser;
import com.msk.common.utils.StringUtils;
import com.msk.framework.web.utils.TokenUtils;
import com.msk.sys.domain.Dict;
import com.msk.sys.domain.User;
import com.msk.sys.service.DictService;
import com.msk.sys.utils.DictMskUtils;
import com.msk.sys.utils.createNumber;
import com.msk.wlhy.domain.*;
import com.msk.wlhy.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 描述:小程序我的运单Controller
 * @author 作者: yangjy
 * @date 时间: 2023/5/5 10:28
 */
@Api(tags = "我的运单Controller")
@RestController
@RequestMapping("/api/htLogisticsWayBill")
public class HtLogisticsWayBillController extends BaseController {

    @Autowired
    private HtDriverFileService htDriverFileService;
    @Autowired
    private HtSupplierService htSupplierService;
    @Autowired
    private HtLogisticsOrderDetailService htLogisticsOrderDetailService;
    @Autowired
    private HtTransportListService htTransportListService;
    @Autowired
    private HtCarFilesService htCarFilesService;

    @Autowired
    private DictService dictService;

    /**
     * 描述: 小程序端托运单详情数据展示
     * @author yangjy
     * @date 2023/5/5 10:49
     * @param htLogisticsOrderDetail
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "托运单")
    @PostMapping("/shippingOrder")
    public R<?> shippingOrderByPage(@RequestBody HtLogisticsOrderDetail htLogisticsOrderDetail) {
        LoginUser loginUser = TokenUtils.getMpLoginUser();//去拿token
        HtSupplier htSupplier = htSupplierService.getHtSupplierByUserId(loginUser.getLoginId());//去拿userID
        if (htSupplier == null || !htSupplier.getAuditStatus().equals("1")) {
            return R.appFail(400101, "用户未认证");
        }
        htLogisticsOrderDetail.setSupplier(htSupplier);
        htLogisticsOrderDetail.getParams().put("orderByStr", "a.create_date desc");
        startPageJson(htLogisticsOrderDetail.getParams(), "");
        List<Map<String, Object>> list = htLogisticsOrderDetailService.selectShippingOrderList(htLogisticsOrderDetail);
        List<Dict> typeDictList = DictMskUtils.getDictListNew("goods_type");
        for (Map<String, Object> goods : list) {
            String goodsType = StringUtils.getString(goods.get("goodsType"));
            String goodsTypeAlias = DictMskUtils.getDictLabelNew(goodsType, typeDictList, "");
            goods.put("goodsTypeAlias", goodsTypeAlias);
            String publishWay = StringUtils.getString(goods.get("publishWay"));
            if ("1".equalsIgnoreCase(publishWay)) {
                goods.put("publishWayAlias", "直接发布");
            } else if ("2".equalsIgnoreCase(publishWay)) {
                goods.put("publishWayAlias", "定向发布");
            } else if ("3".equalsIgnoreCase(publishWay)) {
                goods.put("publishWayAlias", "竞价模式");
            } else {
                goods.put("publishWayAlias", publishWay);
            }
        }
        return R.appOk(getDataTable(list));
    }

    /**
     * 描述: 托运单详情
     * @author yangjy
     * @date 2023/5/5 11:09
     * @param htLogisticsOrderDetail
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "托运单详情")
    @PostMapping(value = "/shippingOrderDetails")
    public R<?> shippingOrderDetails(@RequestBody HtLogisticsOrderDetail htLogisticsOrderDetail) {
        HtLogisticsOrderDetail list = htLogisticsOrderDetailService.findListById(htLogisticsOrderDetail);
        String goodType = DictMskUtils.getDictLabel(list.getGoodsType(), "goods_type", "");
        list.setGoodsTypeAlias(goodType);
        return R.appOk(list);
    }

    /**
     * 描述: 小程序派车单列表
     * @author yangjy
     * @date 2023/5/6 11:17
     * @param htTransportList
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "派车单")
    @PostMapping("/htTransportListByPage")
    public R<?> htTransportListByPage(@RequestBody HtTransportList htTransportList) {
        HtSupplier htSupplier = htSupplierService.getHtSupplierByUserId(TokenUtils.getMpLoginUser().getLoginId());
        if (htSupplier == null || !htSupplier.getAuditStatus().equals("1")) {
            return R.appFail(400101, "用户未认证");
        }
        htTransportList.setSupplierUser(htSupplier.getId());
        htTransportList.getParams().put("orderByStr", "a.create_date desc");
        startPageJson(htTransportList.getParams(), "");
        List<Map<String, Object>> list = htTransportListService.findHtTransportList(htTransportList);
        List<Dict> insuranceCode = DictMskUtils.getDictListNew("insurance_code");
        String isOverload = dictService.findByTypeAndLabel("is_overload", "overload_setting"); //是否允许超载
        for (Map<String, Object> ls : list) {
            String insuranceCompanyCode = StringUtils.getString(ls.get("insuranceCompanyCode"));
            String setInsuranceCompanyCodeAlias = DictMskUtils.getDictLabelNew(insuranceCompanyCode, insuranceCode, "");
            ls.put("insuranceCompanyCodeAlias", setInsuranceCompanyCodeAlias);
            String isEnter = StringUtils.getString(ls.get("isEnter"));
            if ("0".equals(isEnter) || "2".equals(isEnter)) {
                ls.put("waybillStatus", "5");
            }
            String isPay = StringUtils.getString(ls.get("isPay"));
            if ("1".equals(isPay)) {
                ls.put("waybillStatus", "4");
            }
            ls.put("isOverload", isOverload);
        }
        return R.appOk(getDataTable(list));
    }

    @ApiOperation(value = "我的运单数量")
    @PostMapping(value = "/htTransportCount")
    public R<?> htTransportCount(HtTransportList htTransportList){
        LoginUser loginUser = TokenUtils.getMpLoginUser();//去拿token
        HtSupplier htSupplier = htSupplierService.getHtSupplierByUserId(loginUser.getLoginId());
        if (htSupplier == null || !htSupplier.getAuditStatus().equals("1")) {
            return R.appFail(400101, "用户未认证");
        }
        htTransportList.setSupplierUser(htSupplier.getId());
        List<Map<String, Object>> maps = htTransportListService.htTransportCount(htTransportList);
        return R.appOk(maps);
    }

    /**
     * 描述: 派车单详情
     * @author yangjy
     * @date 2023/5/6 11:50
     * @param htTransportList
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "派车单详情")
    @PostMapping(value = "/dispatchOrderDetails")
    public R<?> dispatchOrderDetails(@RequestBody HtTransportList htTransportList) {
        HtTransportList list = htTransportListService.selectDispatchOrderById(htTransportList);
        String insuranceCompanyCode = DictMskUtils.getDictLabel(list.getInsuranceCompanyCode(), "insurance_code", "");
        String isOverload = dictService.findByTypeAndLabel("is_overload", "overload_setting"); //是否允许超载
        list.setIsOverload(isOverload);
        list.setInsuranceCompanyCodeAlias(insuranceCompanyCode);
        if ("0".equals(list.getIsEnter()) || "2".equals(list.getIsEnter())) {
            list.getHtTransportDetail().setStatus("5");
        }
        if ("1".equals(list.getIsPay())) {
            list.getHtTransportDetail().setStatus("4");
        }
        return R.appOk(list);
    }

    /**
     * 描述: 生成派车单中选择车辆
     * @author yangjy
     * @date 2023/5/10 15:33
     * @param htCarFiles
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "选择车辆")
    @PostMapping("/htCarFilesByTransportStatus")
    public R<?> htCarFilesByTransportStatus(@RequestBody HtCarFiles htCarFiles) {
        LoginUser loginUser = TokenUtils.getMpLoginUser();//去拿token
        HtSupplier supplier = htSupplierService.getHtSupplierByUserId(loginUser.getLoginId());//去拿user id
        htCarFiles.setSupplier(supplier);
        htCarFiles.getParams().put("orderByStr", "u14.driver_status,a.create_date desc");
        startPageJson(htCarFiles.getParams(), "");
        List<Map<String, Object>> list = htCarFilesService.findPageByTransportStauts(htCarFiles);
        List<Dict> car_type = DictMskUtils.getDictListNew("car_type");
        for (Map<String, Object> car : list) {
            String carType = StringUtils.getString(car.get("carType"));
            String carTypeAlias = DictMskUtils.getDictLabelNew(carType, car_type, "");
            car.put("carTypeAlias", carTypeAlias);
        }
        return R.appOk(getDataTable(list));
    }

    /**
     * 描述: 生成派车单中选择司机
     * @author yangjy
     * @date 2023/5/23 14:03
     * @param htDriverFile
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "选择司机")
    @PostMapping(value = {"/htDriverFileByPage1"})
    public R<?> htDriverFileByPage1(@RequestBody HtDriverFile htDriverFile) {
        LoginUser loginUser = TokenUtils.getMpLoginUser();//去拿token
        User userQuery = new User();
        userQuery.setUserIdentity(loginUser.getLoginObject()); //用户身份 1:司机 2:货主 3:承运商
        String belongId = null;
        if ("3".equals(loginUser.getLoginObject())) {
            HtSupplier supplier = htSupplierService.getHtSupplierByUserId(loginUser.getLoginId());
            if (supplier != null) {
                belongId = supplier.getId();
            }
        }
        htDriverFile.setIsPassCheck("1");
        htDriverFile.setUser(userQuery);
        htDriverFile.setBelongId(belongId);
        htDriverFile.getParams().put("orderByStr", "a.driver_status,a.create_date desc");
        startPageJson(htDriverFile.getParams(), "");
        List<Map<String, Object>> list = htDriverFileService.findPage1(htDriverFile);
        List<Dict> car_type = DictMskUtils.getDictListNew("car_type");
        for (Map<String, Object> car : list) {
            String carType = StringUtils.getString(car.get("carType"));
            String carTypeAlias = DictMskUtils.getDictLabelNew(carType, car_type, "");
            car.put("carTypeAlias", carTypeAlias);
        }
        return R.appOk(getDataTable(list));
    }

    /**
     * 描述: 同一单多次派车时检查派车数量
     * @author yangjy
     * @date 2023/5/23 9:43
     * @param map
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "同一单多次派车时检查派车数量")
    @PostMapping(value = "/checkCarCount")
    public R<?> checkCarCount(@RequestBody Map<String, String> map) {
        Map<String, Object> result = Maps.newHashMap();
        try {
            int i = htTransportListService.checkCarCount(map.get("id"));
            result.put("carCount", i++);
            result.put("success", true);
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "系统异常");
        }
        return R.appOk(result);
    }

    /**
     * 描述: 生成派车单
     * @author yangjy
     * @date 2023/5/23 10:29
     * @param htTransportList
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "生成派车单")
    @PostMapping(value = "/save")
    public R<?> save(@RequestBody HtTransportList htTransportList) {
        LoginUser mpLoginUser = TokenUtils.getMpLoginUser();
        Map<String, Object> result = Maps.newHashMap();
        try {
            String message = validateModel(htTransportList);
            if (StringUtils.isNotBlank(message)) {
                result.put("flag", false);
                result.put("message", message);
                return R.appOk(result);
            }
            if (htTransportList.getStatus().equals("2") && htTransportList.getDispatchTime() == null) { //已派车 记录派车时间
                htTransportList.setDispatchTime(new Date());
            }
            HtDriverFile driver = new HtDriverFile();
            String htCode = DictMskUtils.getDictLabel("PCD", "ht_code", "");
            String dispatchCarNumber = createNumber.getNewOrderNo(htCode);//生成新派车单号
            String barCode = dispatchCarNumber.substring(htCode.length()).replaceAll("-", "");//生成条码
            htTransportList.setDispatchCarNumber(dispatchCarNumber);
            htTransportList.setBarCode(barCode);
            htTransportList.setCreateBy(new User(mpLoginUser.getLoginId()));
            //获取appId
            String messageString = "保存派车单管理成功";
            htTransportListService.saveDataNew(htTransportList);
            String driverId = htTransportList.getAttstr01();
            driver.setId(driverId);
            driver.setDriverStatus("1");//待运
            htDriverFileService.updatedriverStatus(driver);
            result.put("flag", true);
            result.put("message", messageString);
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", e.toString());
        }
        return R.appOk(result);
    }

    /**
     * 描述: 取消运单
     * @author yangjy
     * @date 2023/6/20 11:08
     * @param map
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "取消运单")
    @PostMapping(value = "/delete")
    public R<?> delete(@RequestBody Map<String, String> map) {
        Map<String, Object> result = Maps.newHashMap();
        try {
            int id = htTransportListService.findInfoById(map.get("id"));
            if (id > 0) {
                result.put("flag", false);
                result.put("message", "选择删除的数据已发运，不允许取消运单");
                return R.appOk(result);
            }
            int i = htTransportListService.deleteIds(map.get("id"));
            result.put("flag", true);
            result.put("message", "取消" + i + "条运单成功");
        } catch (Exception e) {
            result.put("flag", false);
            result.put("message", e.toString());
        }
        return R.appOk(result);
    }
    /**
     * 描述: 获取运单录入需要的数据
     * @author yangjy
     * @date 2023/7/27 13:56
     * @param map
     * @return com.msk.common.core.domain.R<?>
     */
    @ApiOperation(value = "获取运单录入需要的数据")
    @PostMapping(value = "/entryOfWaybill")
    public R<?> entryOfWaybill(@RequestBody Map<String,Object> map){
        String id = String.valueOf(map.get("id"));
        Map<String,Object> waybillData = htTransportListService.entryOfWaybill(id);
        String priceWayAlias = String.valueOf(waybillData.get("priceWay"));
        if("1".equals(priceWayAlias)){
            waybillData.put("priceWayAlias","吨/公里");
        }else if("2".equals(priceWayAlias)){
            waybillData.put("priceWayAlias","整车");
        }else if("3".equals(priceWayAlias)){
            waybillData.put("priceWayAlias","元/吨");
        }
        double goodsWeight = Double.parseDouble(StringUtils.getString(waybillData.get("goodsWeight")));
        double realGoodsWeight = Double.parseDouble(StringUtils.getString(waybillData.get("realGoodsWeight")));
        double remainingGoodsWeight = 0;
        if (goodsWeight != 0) {
            remainingGoodsWeight = goodsWeight - realGoodsWeight;
        }
        String isOverload = dictService.findByTypeAndLabel("is_overload", "overload_setting"); //是否允许超载
        waybillData.put("remainingGoodsWeight", remainingGoodsWeight);
        waybillData.put("isOverload", isOverload);
        return R.appOk(waybillData);
    }
}
